<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/7/4
 * Time: 11:16
 */

namespace app\callback\controller;


use app\common\model\teacher\TeacherEssay;
use think\Env;
use think\Exception;
use think\Log;

class News
{

    public function stock(){
        $this->mylog(date('H:m') ,json_encode($_POST) , 'test');
        // 此处需修改为你的神箭手账户的"user_secret"
        // 神箭手控制台"用户中心"的"用户密钥"就是"user_secret"
        try{
            $user_secret = Env::get('shenjian.APP_SECRET');
            $sign2 = $_POST['sign2']??'';
            $url = $_POST['url']??'';
            $timestamp = $_POST['timestamp']??'';
            if ($url && md5($url . $user_secret . $timestamp) === $sign2){
                $essay = json_decode($_POST['data'],true);
                if(!empty($essay)){
                    $data=[
                        'ref_source'=>json_encode(['url'=>$url,'timestamp'=>$timestamp,'sign2'=>$sign2],JSON_UNESCAPED_UNICODE),
                        'category'=>0,
                        'title'=>$essay['title']??'',
                        'content'=>$essay['content']??'',
                        'created'=>isset($essay['date']) ? date('Y-m-d H:i:s',$essay['date']) :'',
                        'tags'=>'',
                        'teacher_id'=>0
                    ];
                    $model=new TeacherEssay();
                    $res=$model->data($data)->save();
                }
            }
        }catch (Exception $e){
            $this->mylog('sql_error' , $e->getMessage() , 'shenjianshou');
        }

    }

    public function mylog($mark, $log_content, $keyp = "") {
        $max_size = 30000000;
        if ($keyp == "") {
            $log_filename = RUNTIME_PATH . 'log/' . date('Ym-d') . ".log";
        } else {
            $log_filename = RUNTIME_PATH . 'log/' . $keyp . ".log";
        }

        if (file_exists($log_filename) && (abs(filesize($log_filename)) > $max_size)) {
            rename($log_filename, dirname($log_filename) . DS . date('Ym-d-His') . $keyp . ".log");
        }

        $t = microtime(true);
        $micro = sprintf("%06d", ($t - floor($t)) * 1000000);
        $d = new \DateTime (date('Y-m-d H:i:s.' . $micro, $t));
        if(is_array($log_content)){
            $log_content = JSONReturn($log_content);
        }

        file_put_contents($log_filename, '   ' . $d->format('Y-m-d H:i:s u') . " key：" . $mark . "\r\n" . $log_content . "\r\n------------------------ --------------------------\r\n", FILE_APPEND);
    }

}